package com.yiwei.hdb.fragment;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.bumptech.glide.Glide;
import com.yiwei.hdb.R;
import com.yiwei.hdb.activity.InviteRecordActivity;
import com.yiwei.hdb.activity.V2MyQrcodeActivity;
import com.yiwei.hdb.activity.WebViewActivity;
import com.yiwei.hdb.adapter.MainHomeOrderAdapter;
import com.yiwei.hdb.api.Api;
import com.yiwei.hdb.api.bean.PrizeIndexBean;
import com.yiwei.hdb.constant.Const;
import com.yiwei.hdb.constant.UserGlobal;
import com.yiwei.hdb.model.PrizeIndexModel;
import com.yiwei.hdb.util.RxLifeUtil;
import com.yiwei.hdb.util.Util;
import com.yiwei.hdb.view.V19RelativeLayout;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.bumptech.glide.load.DecodeFormat.PREFER_ARGB_8888;

/**
 * Created by xsooy-pc on 18-7-24.
 */

public class MainHomePrizeV2Fragment extends BaseFragment {

    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.txt_user)
    TextView txtUser;
    @BindView(R.id.txt_level)
    SuperButton txtLevel;
    @BindView(R.id.btn_my_qrcode)
    LinearLayout btnMyQrcode;
    @BindView(R.id.layout_title)
    V19RelativeLayout layoutTitle;
    //    @BindView(R.id.view_bottom)
//    View viewBottom;
    @BindView(R.id.btn_rule)
    SuperButton btnRule;
    @BindView(R.id.txt_invite_num)
    TextView txtInviteNum;
    @BindView(R.id.txt_money_num)
    TextView txtMoneyNum;
    @BindView(R.id.txt_thing_num)
    TextView txtThingNum;
    @BindView(R.id.btn_invite)
    TextView btnInvite;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.img_icon_one)
    ImageView imgIconOne;
    @BindView(R.id.txt_user_one)
    TextView txtUserOne;
    @BindView(R.id.layout_float_one)
    RelativeLayout layoutFloatOne;
    @BindView(R.id.img_icon_two)
    ImageView imgIconTwo;
    @BindView(R.id.txt_user_two)
    TextView txtUserTwo;
    @BindView(R.id.layout_float_two)
    RelativeLayout layoutFloatTwo;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.btn_invite_friend)
    SuperButton btnInviteFriend;
    @BindView(R.id.img_total_bg)
    ImageView imgTotalBg;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.img_bolang)
    ImageView imgBolang;
    @BindView(R.id.layout_bolang)
    LinearLayout layoutBolang;
    private ObjectAnimator animation;
    private ObjectAnimator animation1;
    private int num;
    private MainHomeOrderAdapter mainHomeOrderAdapter;
    //    private MainHomePrizeAdapter mainHomePrizeAdapter;
    private List<PrizeIndexModel.DataBean.InviteListBean> invite_list;
    private int poi = 0;
    private String week_num = "";
    private Unbinder unbinder;
    //    private List<PrizeIndexModel.DataBean.RewardListBean> reward_list;
    private List<PrizeIndexModel.DataBean.RewardListBean> total_reward_list;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_main_home_prize_v2;
    }

    @Override
    protected void initView() {
        scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
            @Override
            public void onScrollChanged() {
                refresh.setEnabled(scrollView.getScrollY() == 0);
            }
        });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getPrizeIndex(week_num);
            }
        });
        mainHomeOrderAdapter = new MainHomeOrderAdapter(getContext());
        list.setNestedScrollingEnabled(false);
        list.setAdapter(mainHomeOrderAdapter);


//        Glide.with(this).load(R.mipmap.img_main_invite_bg).into(imgTotalBg);

//        Glide.with(this).load(R.mipmap.img_bolang).asBitmap().format(PREFER_ARGB_8888).into(imgBolang);
//        Glide.with(this).load(R.mipmap.img_bolang).into(imgBolang);
        initAnimation();

    }

    private void initAnimation() {
        animation = ObjectAnimator.ofFloat(layoutFloatOne, "alpha", 0f, 0.5f, 1f, 1f, 0f);
        animation.setRepeatCount(-1);
        animation.setDuration(5000);
        animation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                txtUserOne.setText(invite_list.get(0).mobile + invite_list.get(0).name + "\n" + invite_list.get(0).text);
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                int poi = num++ % invite_list.size();
                txtUserOne.setText(invite_list.get(poi).mobile + invite_list.get(poi).name + "\n" + invite_list.get(poi).text);

            }
        });

        animation1 = ObjectAnimator.ofFloat(layoutFloatTwo, "alpha", 0f, 0.5f, 1f, 1f, 0f);
        animation1.setRepeatCount(-1);
        animation1.setDuration(5000);
        animation1.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                int poi = num++ % invite_list.size();
                txtUserTwo.setText(invite_list.get(poi).mobile + invite_list.get(poi).name + "\n" + invite_list.get(poi).text);
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                int secpoi = num++ % invite_list.size();
                txtUserTwo.setText(invite_list.get(secpoi).mobile + invite_list.get(secpoi).name + "\n" + invite_list.get(secpoi).text);
                if (num >= invite_list.size()) {
                    num = 0;
                }
            }
        });
    }


    public void getPrizeIndex(String week_num) {
        refresh.setRefreshing(true);
        PrizeIndexBean bean = new PrizeIndexBean();
        bean.week_num = week_num;
        Api.api_service.getPrizeIndex(bean).compose(RxLifeUtil.checkOn(getContext())).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }

                }).
                subscribe(result -> {

                    txtLevel.setText(result.data.invite_level);
                    PrizeIndexModel.DataBean.StatisticsBean statisticsData = result.data.statistics;
                    txtInviteNum.setText(statisticsData.register);
                    txtMoneyNum.setText(statisticsData.total);
                    txtThingNum.setText(statisticsData.ranking);
//                    公告栏

//                    邀请列表
                    invite_list = result.data.invite_list;
//                    开启动画
                    if (invite_list != null && invite_list.size() != 0) {
                        if (animation.isRunning()) {
                            animation.cancel();
                        }
                        if (animation1.isRunning()) {
                            animation1.cancel();
                        }
                        animation.start();
                        txtUser.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                animation1.start();
                            }
                        }, 3000);
                    }


//                    ======================================================================
//                    reward_list = result.data.reward_list;
                    total_reward_list = result.data.total_reward_list;


                    mainHomeOrderAdapter.update(total_reward_list);
                });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (UserGlobal.checkLogin()) {
            getPrizeIndex(week_num);
//            int sex = UserGlobal.getSex();
//            if (sex == 0) {
//                Glide.with(getActivity()).load(UserGlobal.getHeader()).dontAnimate().placeholder(R.mipmap.img_main_prize_icon).error(R.mipmap.img_main_prize_icon).into(imgIcon);
//            } else {
//                Glide.with(getActivity()).load(UserGlobal.getHeader()).dontAnimate().placeholder(R.mipmap.img_my_boy).error(R.mipmap.img_my_boy).into(imgIcon);
//            }
//            Glide.with(getActivity()).load(UserGlobal.getHeader()).dontAnimate().placeholder(R.mipmap.img_main_prize_icon).error(R.mipmap.img_main_prize_icon).into(imgIcon);
            txtUser.setText(UserGlobal.getUserName());
        }

//        gifDrawable.start();
        if (invite_list != null && invite_list.size() != 0) {
            animation.start();
            txtUser.postDelayed(new Runnable() {
                @Override
                public void run() {
                    animation1.start();
                }
            }, 3000);
        }

    }

    @Override
    public void onPause() {
        super.onPause();
//        gifDrawable.pause();
        animation.cancel();
        animation1.cancel();
    }


    @OnClick({R.id.btn_my_qrcode, R.id.btn_rule, R.id.btn_invite})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.btn_my_qrcode:
                if (Util.checkLogin(getActivity()))
                    Util.startActivity(getContext(), V2MyQrcodeActivity.class);
                break;
            case R.id.btn_rule:
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "活动规则");
                intent.putExtra("url", Const.ACT_RULES);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                break;
            case R.id.btn_invite:
                if (Util.checkLogin(getActivity()))
                    Util.startActivity(getContext(), InviteRecordActivity.class);
                break;
        }
    }


    @OnClick(R.id.btn_invite_friend)
    public void onViewClicked() {
        if (Util.checkLogin(getActivity()))
            Util.startActivity(getContext(), V2MyQrcodeActivity.class);
    }
}
